﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Brettle.Web.NeatUpload;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using ud_gSDMS.Code_Service;
using Image = System.Web.UI.WebControls.Image;

namespace ud_gSDMS.contract
{
    public partial class Contract_HostDomain_Edit : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string _id;
        private SiteUser _siteUser;
        protected String cacheDependencyKey;

        void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //if (!UserCanEditPage() || !UserCanViewPage())
                //{
                //    SiteUtils.RedirectToLoginPage(this);
                //}

                _siteUser = SiteUtils.GetCurrentSiteUser();

                
                
                //SiteUser.ConfirmRegistration()
                if (_siteUser == null)
                {
                    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                }
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                    

                    if (!string.IsNullOrEmpty(Request["id"]))
                    {
                        _id = Request["id"];
                        LoadData(_id);
                    }
                    else
                    {
                        LoadGridHostPackage();
                        LoadGridDomain();
                    }
                }
                InsertScript();
            }catch(Exception exception)
            {
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            if (string.IsNullOrEmpty(_id))
            {
                txtContract_Code.Text = gSDMS_BL.ud_gSDMS_HOSTING_CONTRACT_AutoGenCode();
            }

            var minDay = Convert.ToDateTime(ConfigurationManager.AppSettings["MinDay"]);
            var maxDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);

            if (Session["URLCURRENT"] != null)
            {
                lnkGoback.HRef = (string) Session["URLCURRENT"];
                Session["URLCURRENT"] = null;
            }
            ud_Utilities.Utilities.AddConfirmButton(btnDelere, "Do you want to delete this item?");


        }

        private void InsertScript()
        {
            if (!Page.ClientScript.IsStartupScriptRegistered(typeof(System.Web.UI.Page), "common_js"))
                Page.ClientScript.RegisterStartupScript(typeof (System.Web.UI.Page), "common_js", "\n<script src=\""
                                                                                                  + Page.ResolveUrl("~/ClientScript/gSDMS/common.js") +
                                                                                                  "\" type=\"text/javascript\"></script>");
        }

        private DataTable CreateTable(string key)
        {
            var dataTable = new DataTable();
            DataColumn col;
            if (key == "host")
            {
                col = new DataColumn("Hosting_Contract_Hosting_ID");
                dataTable.Columns.Add(col);

                col = new DataColumn("Hosting_Contract_ID");
                dataTable.Columns.Add(col);

                col = new DataColumn("Cat_Hosting_ID");
                dataTable.Columns.Add(col);

                col = new DataColumn("HostPackageName");
                dataTable.Columns.Add(col);

                col = new DataColumn("Size");
                dataTable.Columns.Add(col);

                col = new DataColumn("Start_Date");
                dataTable.Columns.Add(col);

                col = new DataColumn("End_Date");
                dataTable.Columns.Add(col);

                col = new DataColumn("Domain");
                dataTable.Columns.Add(col);

                col = new DataColumn("Hosting_Content");
                dataTable.Columns.Add(col);
            }
            else if (key == "domain")
            {
                col = new DataColumn("Hosting_Contract_Domain_ID");
                dataTable.Columns.Add(col);

                col = new DataColumn("Hosting_Contract_ID");
                dataTable.Columns.Add(col);

                col = new DataColumn("Domain_Name");
                dataTable.Columns.Add(col);

                col = new DataColumn("World_Domain");
                dataTable.Columns.Add(col);

                col = new DataColumn("VietNam_Domain");
                dataTable.Columns.Add(col);
                
                col = new DataColumn("Start_Date");
                dataTable.Columns.Add(col);

                col = new DataColumn("End_Date");
                dataTable.Columns.Add(col);

                col = new DataColumn("Price");
                dataTable.Columns.Add(col);

                col = new DataColumn("Domain_Content");
                dataTable.Columns.Add(col);
            }
            return dataTable;
        }

        private void LoadComboHostPackage(DropDownList cbo)
        {
            cbo.DataValueField = "CAT_Hosting_ID";
            cbo.DataTextField = "Name2";
            cbo.DataSource = gSDMS_BL.ud_gSDMS_CAT_HOSTING_PACKAGE_Lst_AddSize();
            cbo.DataBind();
            cbo.Items.Insert(0, "");
        }

        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;

            var o = gSDMS_BL.ud_gSDMS_HOSTING_CONTRACT_Get(id);
            if (o != null)
            {
 
                    if (!gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "14|12|1") && _siteUser.UserId != o.CreatedBy)
                    {
                        WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                    }
                hidId.Value = o.Hosting_Contract_ID.ToString();
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToString();
                txtContract_Code.Text = o.Contract_Code;
                txtCompany_Name.Text = o.Company_Name;
                txtAdmin_Name.Text = o.Admin_Name;
                txtAdmin_Phone.Text = o.Admin_Phone;
                txtAdmin_Email.Text = o.Admin_Email;
                txtCompany_Address.Text = o.Company_Address;
                txtNote.Text = o.Note;

                btnUpload.Visible = true;

                

                if (o.ud_gSDMS_HOSTING_CONTRACT_HOSTINGs.Count > 0)
                {
                    var dataTable = CreateTable("host");
                    foreach (ud_gSDMS_HOSTING_CONTRACT_HOSTING h in o.ud_gSDMS_HOSTING_CONTRACT_HOSTINGs)
                    {
                        var newRow = dataTable.NewRow();

                        newRow["Hosting_Contract_Hosting_ID"] = h.Hosting_Contract_Hosting_ID;
                        newRow["Hosting_Contract_ID"] = h.Hosting_Contract_ID;
                        newRow["Cat_Hosting_ID"] = h.Cat_Hosting_ID;
                        newRow["Start_Date"] = h.Start_Date == null ? "" : h.Start_Date.Value.ToString("dd/MM/yyyy");
                        newRow["End_Date"] = h.End_Date == null ? "" : h.End_Date.Value.ToString("dd/MM/yyyy");
                        newRow["HostPackageName"] = h.ud_gSDMS_CAT_HOSTING_PACKAGE.Name;
                        newRow["Size"] = h.ud_gSDMS_CAT_HOSTING_PACKAGE.Size;
                        newRow["Hosting_Content"] = h.Hosting_Content;
                        newRow["Domain"] = h.Domain;
                        
                        dataTable.Rows.Add(newRow);
                        ViewState["listHostPackage"] = dataTable;
                    }
                }
                if (o.ud_gSDMS_HOSTING_CONTRACT_DOMAINs.Count > 0)
                {
                    var dataTable = CreateTable("domain");
                    foreach (ud_gSDMS_HOSTING_CONTRACT_DOMAIN h in o.ud_gSDMS_HOSTING_CONTRACT_DOMAINs)
                    {
                        var newRow = dataTable.NewRow();

                        newRow["Hosting_Contract_Domain_ID"] = h.Hosting_Contract_Domain_ID;
                        newRow["Hosting_Contract_ID"] = h.Hosting_Contract_ID;
                        newRow["Domain_Name"] = h.Domain_Name;
                        newRow["Start_Date"] = h.Start_Date == null ? "" : h.Start_Date.Value.ToString("dd/MM/yyyy");
                        newRow["End_Date"] = h.End_Date == null ? "" : h.End_Date.Value.ToString("dd/MM/yyyy");
                        newRow["World_Domain"] = h.World_Domain;
                        newRow["VietNam_Domain"] = h.VietNam_Domain;
                        newRow["Domain_Content"] = h.Domain_Content;
                        newRow["Price"] = h.Price;

                        dataTable.Rows.Add(newRow);
                        ViewState["listDomain"] = dataTable;
                    }
                }

                
            }

            
            LoadGridHostPackage();
            LoadGridDomain();
            BindAttachments();

        }

        

        private void LoadGridHostPackage()
        {
            DataTable dataTable;
            if (ViewState["listHostPackage"] != null)
            {
                dataTable = (DataTable) ViewState["listHostPackage"];
                if (dataTable.Rows.Count == 0)
                {
                    dataTable.Rows.Add(dataTable.NewRow());
                }
            }
            else
            {
                dataTable = CreateTable("host");
                dataTable.Rows.Add(dataTable.NewRow());
            }
            grdHostPackage.DataSource = dataTable;
            grdHostPackage.DataBind();
            

            if (grdHostPackage.FooterRow != null)
            {
                var cboCAT_Hosting_ID = ((DropDownList) grdHostPackage.FooterRow.FindControl("cboCAT_Hosting_ID"));
                LoadComboHostPackage(cboCAT_Hosting_ID);
            }

        }
        private void LoadGridDomain()
        {
            DataTable dataTable;
            if (ViewState["listDomain"] != null)
            {
                dataTable = (DataTable)ViewState["listDomain"];
                if (dataTable.Rows.Count == 0)
                {
                    dataTable.Rows.Add(dataTable.NewRow());
                }
            }
            else
            {
                dataTable = CreateTable("domain");
                // vao du lieu vao mot cot
                //var r = dataTable.NewRow();
                //r["d"] = "";
              //  dataTable.Rows.Add(r);
                dataTable.Rows.Add(dataTable.NewRow());
            }
            grdDomain.DataSource = dataTable;
            grdDomain.DataBind();
        }


        #region event
        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool isUpload = hidId.Value == "";

                _id = hidId.Value;
                var userSite = SiteUtils.GetCurrentSiteUser();
                gSDMS_BL.ud_gSDMS_HOSTING_CONTRACT_Upd(ref _id, txtContract_Code.Text, txtCompany_Name.Text, txtCompany_Address.Text, txtAdmin_Name.Text, txtAdmin_Phone.Text, txtAdmin_Email.Text, txtNote.Text, userSite.UserId.ToString(),
                                                       string.IsNullOrEmpty(hidCreatedOn.Value) ? DateTime.Now : Convert.ToDateTime(hidCreatedOn.Value),  true,
                                                       (DataTable) ViewState["listHostPackage"],
                                                       (DataTable) ViewState["listDomain"]);
                hidId.Value = _id;

                

                if (isUpload)
                {
                    UploadFile();
                    
                }
                WebUtils.SetupRedirect(this, SiteRoot + "/gsdmsmodule/contract/Contract_HostDomain.aspx");
                
            }
            catch (Exception ex)
            {
                lblMes.Text = ex.Message;
                lblMes.Visible = true;
            }
        }
        void btnDelere_Click(object sender, EventArgs e)
        {
            if (hidId.Value == "") return;
            try
            {
                _id = hidId.Value;
                var userSite = SiteUtils.GetCurrentSiteUser();
                gSDMS_BL.ud_gSDMS_HOSTING_CONTRACT_Del_DeActive(_id);
                Response.Redirect("/gsdmsmodule/contract/Contract_HostDomain.aspx?pageid=29");
            }
            catch (Exception ex)
            {
                lblMes.Text = ex.Message;
                lblMes.Visible = true;
            }
        }
 

        #region event grdHostPackage
        void grdHostPackage_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "insert":
                    {
                        DataTable dataTable;
                        if (ViewState["listHostPackage"] == null)
                            dataTable = CreateTable("host");
                        else
                            dataTable = (DataTable) ViewState["listHostPackage"];

                        var row = dataTable.NewRow();
                        var cboCAT_Hosting_ID = (DropDownList) grdHostPackage.FooterRow.FindControl("cboCAT_Hosting_ID");
                        var catHostPackage = gSDMS_BL.ud_gSDMS_CAT_HOSTING_PACKAGE_Get(cboCAT_Hosting_ID.SelectedValue);

                        row["Cat_Hosting_ID"] = catHostPackage.CAT_Hosting_ID;
                        row["HostPackageName"] = catHostPackage.Name;
                        row["Size"] = catHostPackage.Size;
                        row["Start_Date"] = ((TextBox) grdHostPackage.FooterRow.FindControl("txtStart_Date")).Text;
                        row["End_Date"] = ((TextBox) grdHostPackage.FooterRow.FindControl("txtEnd_Date")).Text;
                        row["Hosting_Content"] = ((TextBox)grdHostPackage.FooterRow.FindControl("txtHosting_Content")).Text;
                        row["Domain"] = ((TextBox)grdHostPackage.FooterRow.FindControl("txtHosting_Domain")).Text;
                        dataTable.Rows.Add(row);

                        ViewState["listHostPackage"] = dataTable;

                        grdHostPackage.EditIndex = -1;
                        LoadGridHostPackage();
                        break;
                    }
                case "insert-empty-row":
                    {
                        if (ViewState["listHostPackage"] == null) break;

                        var dataTable = (DataTable) ViewState["listHostPackage"];

                        if (dataTable.Rows.Count == 1) break; //Khi chi co 1 dong dau tien

                        var index = Convert.ToInt32(e.CommandArgument);
                        if (index == dataTable.Rows.Count || dataTable.Rows[index - 1]["Cat_Hosting_ID"].ToString() == "") break; //Khi dang o row cuoi cung
                        
                        dataTable.Rows.InsertAt(dataTable.NewRow(), index);

                        grdHostPackage.EditIndex = index;
                        LoadGridHostPackage();
                        break;
                    }
            }
        }

        void grdHostPackage_RowEditing(object sender, GridViewEditEventArgs e)
        {
             grdHostPackage.EditIndex = e.NewEditIndex;

            LoadGridHostPackage();
        }

        void grdHostPackage_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DataTable  dataTable;
            if (ViewState["listHostPackage"] == null)
                dataTable = CreateTable("host");
            else
                dataTable = (DataTable)ViewState["listHostPackage"];
            var i = e.RowIndex + grdDomain.PageSize * grdDomain.PageIndex;

            DataRow row;
            if (dataTable.Rows.Count>0)
            {
                row = dataTable.Rows[i];
            }
            else
            {
                row = dataTable.NewRow();
                dataTable.Rows.Add(row);
            }

            var catHostPackage = gSDMS_BL.ud_gSDMS_CAT_HOSTING_PACKAGE_Get(((DropDownList) grdHostPackage.Rows[e.RowIndex].FindControl("cboCAT_Hosting_ID")).SelectedValue);

            row["Cat_Hosting_ID"] = catHostPackage.CAT_Hosting_ID;
            row["HostPackageName"] = catHostPackage.Name;
            row["Size"] = catHostPackage.Size;
            row["Start_Date"] = ((TextBox)grdHostPackage.Rows[e.RowIndex].FindControl("txtStart_Date")).Text;
            row["End_Date"] = ((TextBox)grdHostPackage.Rows[e.RowIndex].FindControl("txtEnd_Date")).Text;
            row["Hosting_Content"] = ((TextBox)grdHostPackage.Rows[e.RowIndex].FindControl("txtHosting_Content")).Text;
            row["Domain"] = ((TextBox)grdHostPackage.Rows[e.RowIndex].FindControl("txtHosting_Domain")).Text;

            ViewState["listHostPackage"] = dataTable;
            
            grdHostPackage.EditIndex = -1;
            LoadGridHostPackage();
        }

        void grdHostPackage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            var i = e.RowIndex;
            var dataTable = (DataTable)ViewState["listHostPackage"];
            if (dataTable.Rows[i]["Cat_Hosting_ID"].ToString() == "")
            {
                dataTable.Rows.Remove(dataTable.Rows[i]);
            }

            grdHostPackage.EditIndex = -1;
            LoadGridHostPackage();
        }

        void grdHostPackage_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (ViewState["listHostPackage"]!=null)
            {
                var dataTable = (DataTable)ViewState["listHostPackage"];
                var index = e.RowIndex + grdHostPackage.PageSize * grdHostPackage.PageIndex;
                var row = dataTable.Rows[index];

                //Delete
                if (row["CAT_Hosting_ID"].ToString() != "")
                {
                    dataTable.Rows.Remove(row);
                    ViewState["listHostPackage"] = dataTable;
                    LoadGridHostPackage();
                }
            }
        }

        void grdHostPackage_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.FindControl("cboCAT_Hosting_ID") != null)
            {
                var cboCAT_Hosting_ID = (DropDownList) e.Row.FindControl("cboCAT_Hosting_ID");               
                LoadComboHostPackage(cboCAT_Hosting_ID);
            }
        }

        void grdHostPackage_PreRender(object sender, EventArgs e)
        {
            int index = grdHostPackage.EditIndex;
            if (index != -1)
            {
                if (grdHostPackage.Rows[index].FindControl("cboCAT_Hosting_ID") != null)
                {
                    DataTable dataTable = (DataTable)ViewState["listHostPackage"];
                    var cboCAT_Hosting_ID = (DropDownList)grdHostPackage.Rows[index].FindControl("cboCAT_Hosting_ID");

                    if (dataTable.Rows[index]["Cat_Hosting_ID"] != null)
                    {

                        cboCAT_Hosting_ID.SelectedValue = dataTable.Rows[index]["Cat_Hosting_ID"].ToString();
                    }
                }
            }
        }

        void grdHostPackage_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdDomain.EditIndex = -1;
            grdHostPackage.PageIndex = e.NewPageIndex;
            LoadGridHostPackage();
        }
        #endregion

        #region event grdDomain
        void grdDomain_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var grd = (GridView) sender;
            switch (e.CommandName)
            {
                case "insert":
                    {
                        DataTable dataTable;
                        if (ViewState["listDomain"] == null)
                            dataTable = CreateTable("domain");
                        else
                            dataTable = (DataTable)ViewState["listDomain"];

                        var row = dataTable.NewRow();
                        row["Domain_Name"] = ((TextBox)grd.FooterRow.FindControl("txtDomain_Name")).Text;
                        row["World_Domain"] = ((RadioButton)grd.FooterRow.FindControl("radWorld_Domain")).Checked;
                        row["VietNam_Domain"] = ((RadioButton)grd.FooterRow.FindControl("radVietNam_Domain")).Checked;
                        row["Start_Date"] = ((TextBox)grd.FooterRow.FindControl("txtStart_Date")).Text;
                        row["End_Date"] = ((TextBox)grd.FooterRow.FindControl("txtEnd_Date")).Text;
                        row["Domain_Content"] = ((TextBox)grd.FooterRow.FindControl("txtDomain_Content")).Text;
                        row["Price"] = ((TextBox)grd.FooterRow.FindControl("txtDomain_Price")).Text.RemoveNonNumeric();
                        
                        dataTable.Rows.Add(row);
                        
                        ViewState["listDomain"] = dataTable;

                        grd.EditIndex = -1;
                        LoadGridDomain();
                        break;
                    }
                case "insert-empty-row":
                    {
                        if (ViewState["listDomain"] == null) break;

                        var dataTable = (DataTable)ViewState["listDomain"];

                        if (dataTable.Rows.Count == 1) break; //Khi chi co 1 dong dau tien

                        var index = Convert.ToInt32(e.CommandArgument);
                        if (index == dataTable.Rows.Count || dataTable.Rows[index - 1]["Domain_Name"].ToString() == "") break; //Khi dang o row cuoi cung hoac row hien tai

                        dataTable.Rows.InsertAt(dataTable.NewRow(), index);

                        grd.EditIndex = index;
                        LoadGridDomain();
                        break;
                    }
            }
        }

        void grdDomain_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grdDomain.EditIndex = e.NewEditIndex ;
            LoadGridDomain();
        }

        void grdDomain_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var grd = (GridView) sender;
            int index = e.RowIndex + grdDomain.PageSize * grdDomain.PageIndex;

            DataTable dataTable;
            if (ViewState["listDomain"] == null)
                dataTable = CreateTable("domain");
            else
                dataTable = (DataTable)ViewState["listDomain"];
            var i = index;
            DataRow row;
            if (dataTable.Rows.Count > 0)
            {
                row = dataTable.Rows[i];
            }
            else
            {
                row = dataTable.NewRow();
                dataTable.Rows.Add(row);
            }
            
            row["Domain_Name"] = ((TextBox)grd.Rows[e.RowIndex].FindControl("txtDomain_Name")).Text;
            row["Start_Date"] = ((TextBox)grd.Rows[e.RowIndex].FindControl("txtStart_Date")).Text;
            row["End_Date"] = ((TextBox)grd.Rows[e.RowIndex].FindControl("txtEnd_Date")).Text;
            row["World_Domain"] = ((RadioButton)grd.Rows[e.RowIndex].FindControl("radWorld_Domain")).Checked;
            row["VietNam_Domain"] = ((RadioButton)grd.Rows[e.RowIndex].FindControl("radVietNam_Domain")).Checked;
            row["Domain_Content"] = ((TextBox)grd.Rows[e.RowIndex].FindControl("txtDomain_Content")).Text;
            row["Price"] = ((TextBox)grd.Rows[e.RowIndex].FindControl("txtDomain_Price")).Text.RemoveNonNumeric();

            ViewState["listDomain"] = dataTable;

            grd.EditIndex = -1;
            LoadGridDomain();
        }

        void grdDomain_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            var i = e.RowIndex;
            var dataTable = (DataTable)ViewState["listDomain"];
            if (dataTable.Rows[i]["Domain_Name"].ToString() == "")
            {
                dataTable.Rows.Remove(dataTable.Rows[i]);
            }

            grdDomain.EditIndex = -1;
            LoadGridDomain();
        }

        void grdDomain_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (ViewState["listDomain"] != null)
            {
                var dataTable = (DataTable)ViewState["listDomain"];
                var index = e.RowIndex + grdDomain.PageSize * grdDomain.PageIndex;
                var row = dataTable.Rows[index];

                //Delete
                if (row["Domain_Name"].ToString() != "")
                {
                    dataTable.Rows.Remove(row);
                    ViewState["listDomain"] = dataTable;
                    LoadGridDomain();
                }
            }
        }

        void grdDomain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.FindControl("radWorld_Domain") != null)
            //{
            //    var radWorld_Domain = (RadioButton)e.Row.FindControl("radWorld_Domain");
            //    if (e.Row.DataItem != null && ((DataRowView)e.Row.DataItem)[4].ToString() != "")
            //        radWorld_Domain.Checked = Convert.ToBoolean(((DataRowView) e.Row.DataItem)[1]);
            //}
        }

        void grdDomain_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdDomain.EditIndex = -1;
            grdDomain.PageIndex = e.NewPageIndex;
            LoadGridDomain();
        }
        #endregion

        void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + e.CommandArgument;
            path = path.Replace("/", "\\");
            switch (e.CommandName)
            {
                case "DeleteItem":
                    var repository = new ud_gSDMS_Attachments();
                    bool a = repository.DeleteItemAttachment(e.CommandArgument.ToString());
                    bool b = repository.Delete(e.CommandArgument.ToString());
                    if (a && b)
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    break;
                case "DownloadItem":
                    {
                        var repository_ = new ud_gSDMS_Attachments();
                        var file = repository_.GetOne(Convert.ToInt32(e.CommandArgument));
                        path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + file.ServerFileName;

                        FileInfo f = new FileInfo(path);

                        if (f.Exists)
                        {

                            Response.Clear();
                            Response.ContentType = "application/octet-stream";
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + Library.RemoveSign4VietnameseString(file.FileName).Replace(" ", "-"));
                            Response.WriteFile(path);
                            Response.End();
                            //if file does not exist
                        }
                        else
                        {
                            Response.Write("This file does not exist.");
                        }
                        break;
                    }

            }
            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        void btnUpload_Click(object sender, EventArgs e)
        {
            UploadFile();
            //WebUtils.SetupRedirect(this, SiteRoot + article.ItemUrl.Replace("~/", "/"));
        }

        int UploadFile()
        {
            var upLoadPath = Page.Server.MapPath(WebUtils.GetApplicationRoot() + "/Data/gSDMSAttachments/");
            int fileID = 0;

            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            if (hidId.Value == "")
            {
                return 0;
            }
            //if (article == null) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            //if ((article.ItemId <= 0) || (article.ModuleId != moduleId)) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            if (file1.HasFile && file1.FileName != null && file1.FileName.Trim().Length > 0)
            {
                var repository = new ud_gSDMS_Attachments();

                string serverFileName = Guid.NewGuid() + ".config";

                var suss = repository.Create(file1.FileName, serverFileName, (int)(file1.ContentLength / 1024), out fileID, OptionForm.HostingDomain.ToString(), hidId.Value);
                if (suss)
                {
                    var destPath = upLoadPath + serverFileName;

                    if (File.Exists(destPath))
                    {
                        File.Delete(destPath);

                    }
                    file1.MoveTo(destPath, MoveToOptions.Overwrite);
                }
                BindAttachments();
            }

            CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
            return fileID;
        }

        
        void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        {
            //if (hidId.Value != "")
            //    DeleteImageFromServer();
        }
        private void BindAttachments()
        {
            var repository = new ud_gSDMS_Attachments();
            rptAttachments.DataSource = repository.GetByItemID(OptionForm.HostingDomain.ToString(), hidId.Value);
            rptAttachments.DataBind();

            lblAttachments.Visible = rptAttachments.Items.Count > 0;
        }
        private void DeleteImageFromServer()
        {
            //string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["gSDMSAttachments"] + article.ImageUrl;
            //thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            //string imageURL = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            //if (File.Exists(imageURL))
            //{
            //    File.Delete(imageURL);
            //}
            //if (File.Exists(thumbnailImageURL))
            //{
            //    File.Delete(thumbnailImageURL);
            //}
        }
        
        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "p.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            var imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            var path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            var ibtnDelete = (ImageButton)e.Item.FindControl("ibtnDelete");
            ud_Utilities.Utilities.AddConfirmButton(ibtnDelete, "Do you want to delete this file?");
        }


        #endregion event


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);

            
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            btnUpload.Click += btnUpload_Click;
            rptAttachments.ItemDataBound += rptAttachments_ItemDataBound;
            rptAttachments.ItemCommand += rptAttachments_ItemCommand;


            btnSave.Click+=btnSave_Click;
            btnDelere.Click += btnDelere_Click;


            grdHostPackage.RowCommand += grdHostPackage_RowCommand;
            grdHostPackage.RowEditing += grdHostPackage_RowEditing;
            grdHostPackage.RowCancelingEdit += grdHostPackage_RowCancelingEdit;
            grdHostPackage.RowUpdating += grdHostPackage_RowUpdating;
            grdHostPackage.RowDeleting += grdHostPackage_RowDeleting;
            grdHostPackage.RowDataBound += grdHostPackage_RowDataBound;
            grdHostPackage.PreRender += grdHostPackage_PreRender;
            grdHostPackage.PageIndexChanging += grdHostPackage_PageIndexChanging;

            grdDomain.RowCommand += grdDomain_RowCommand;
            grdDomain.RowEditing += grdDomain_RowEditing;
            grdDomain.RowCancelingEdit += grdDomain_RowCancelingEdit;
            grdDomain.RowUpdating += grdDomain_RowUpdating;
            grdDomain.RowDeleting += grdDomain_RowDeleting;
            grdDomain.RowDataBound += grdDomain_RowDataBound;
            grdDomain.PageIndexChanging += grdDomain_PageIndexChanging;
            SuppressPageMenu();
        }

        
        
        //void btnFinish_Click(object sender, EventArgs e)
        //{
        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            cacheDependencyKey = "Module-" + moduleId.ToInvariantString();
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }
}